package binary_tree.leetcode.medium;

import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

/**
 * @author bruin_du
 * @description 日程表
 * @date 2022/8/16 21:18
 **/
// 方法一：自定义类并用TreeSet进行大小比较插入
public class OfferII058_MyCalendar {
    private static class Calender implements Comparable<Calender>{
        private int start;
        private int end;

        public Calender(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public int compareTo(Calender calender) {
            if (start >= calender.end) return 1;
            if (end <= calender.start) return -1;
            return 0;
        }
    }

    TreeSet<Calender> set;
    public OfferII058_MyCalendar() {
        set = new TreeSet<>();
    }

    public boolean book(int start, int end) {
        return set.add(new Calender(start, end));
    }
}

//方法二：使用TreeMap
class MyCalendar {
    // 保存的start,end
    TreeMap<Integer, Integer> map;
    public MyCalendar() {
        map = new TreeMap<>();
    }

    public boolean book(int start, int end) {
        // 通过ceilingEntry获取key大等于start的结点,如果end在该结点范围则返回false
        Map.Entry<Integer, Integer> tmp = map.ceilingEntry(start);
        if (tmp != null && tmp.getKey() < end) return false;
        // 通过floorEntry获取key小等于start的结点,如果start在该结点范围则返回false
        tmp = map.floorEntry(start);
        if (tmp != null && tmp.getValue() > start) return false;
        map.put(start, end);
        return true;
    }
}
